package com.xueyi.workflow.service.impl;

import com.xueyi.common.web.entity.service.impl.BaseServiceImpl;
import com.xueyi.workflow.domain.query.RoleProcessPermQuery;
import com.xueyi.workflow.domain.dto.RoleProcessPermDto;
import com.xueyi.workflow.domain.entity.RoleProcessPerm;
import com.xueyi.workflow.manager.RoleProcessPermManager;
import com.xueyi.workflow.correlate.NoneCorrelate;
import com.xueyi.workflow.service.RoleProcessPermService;
import com.xueyi.common.core.web.result.AjaxResult;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;

@Service
public class RoleProcessPermServiceImpl extends BaseServiceImpl<RoleProcessPermQuery, RoleProcessPermDto, NoneCorrelate, RoleProcessPermManager> implements RoleProcessPermService {

    @Override
    @Transactional
    public AjaxResult batchAssign(Long roleId, List<String> processKeys) {
        if (roleId == null) {
            return AjaxResult.error("参数不能为空");
        }
        // 先删除该角色所有流程权限
        RoleProcessPermQuery delQuery = new RoleProcessPermQuery();
        delQuery.setRoleId(roleId);
        List<RoleProcessPermDto> oldList = selectList(delQuery);
        if (oldList != null) {
            for (RoleProcessPermDto dto : oldList) {
                deleteById(dto.getId());
            }
        }
        // 再批量插入新权限（如果有）
        if (processKeys != null && !processKeys.isEmpty()) {
            for (String processKey : processKeys) {
                RoleProcessPermDto dto = new RoleProcessPermDto();
                dto.setRoleId(roleId);
                dto.setProcessKey(processKey);
                insert(dto);
            }
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult batchUnbind(Long roleId, List<String> processKeys) {
        if (roleId == null || processKeys == null || processKeys.isEmpty()) {
            return AjaxResult.error("参数不能为空");
        }
        RoleProcessPermQuery query = new RoleProcessPermQuery();
        query.setRoleId(roleId);
        for (String processKey : processKeys) {
            query.setProcessKey(processKey);
            List<RoleProcessPermDto> list = selectList(query);
            for (RoleProcessPermDto dto : list) {
                deleteById(dto.getId());
            }
        }
        return AjaxResult.success();
    }

    @Override
    public boolean checkPerm(Long roleId, String processKey) {
        RoleProcessPermQuery query = new RoleProcessPermQuery();
        query.setRoleId(roleId);
        query.setProcessKey(processKey);
        List<RoleProcessPermDto> list = selectList(query);
        return list != null && !list.isEmpty();
    }
}
